/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.zookeeper.server;

import org.apache.jute.Record;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.proto.*;
import org.apache.zookeeper.server.DataTree.ProcessTxnResult;
import org.apache.zookeeper.server.NIOServerCnxn.CnxnStats;
import org.apache.zookeeper.server.paxos2.Configuration;
import org.apache.zookeeper.server.paxos2.Mapping;
import org.apache.zookeeper.server.paxos2.MemoryBuffer;
import org.apache.zookeeper.txn.ErrorTxn;
import org.apache.zookeeper.txn.TxnHeader;

import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This Request processor actually applies any transaction associated with a
 * request and services any queries. It is always at the end of a
 * RequestProcessor chain (hence the name), so it does not have a nextProcessor
 * member.
 * <p/>
 * This RequestProcessor counts on ZooKeeperServer to populate the
 * outstandingRequests member of ZooKeeperServer.
 */
public class FinalRequestProcessor implements RequestProcessor {
    private static final Logger LOG = Logger
            .getLogger(FinalRequestProcessor.class);

    ZooKeeperServer zks;

    private LinkedList<Request[]> boloskyRead = new LinkedList<Request[]>();
    
    private static SendResponseThread sender = null;

    public FinalRequestProcessor(ZooKeeperServer zks) {
        this.zks = zks;
        if(sender==null){
        	sender = new SendResponseThread();
        	sender.start();
        }
    }

    private void checkBoloskyRead() {
        Iterator<Request[]> iter = boloskyRead.iterator();
        while (iter.hasNext()) {
            Request[] req = iter.next();
            if (req[0].zxid == zks.getZKDatabase().getDataTreeLastProcessedZxid()) {
                processRequest(req);
                iter.remove();
            } else if (req[0].zxid < zks.getZKDatabase().getDataTreeLastProcessedZxid())
                iter.remove();
        }
    }

    public void processRequest(Request request) {
        throw new RuntimeException("Not implemented");
    }

    public void processRequest(Request[] request) {
	
	long start = System.currentTimeMillis();
        if (request == null || request.length == 0)
            return;
        //System.out.println("final "+request);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing request:: " + request);
        }
        // request.addRQRec(">final");
        long traceMask = ZooTrace.CLIENT_REQUEST_TRACE_MASK;
        if (request[0].type == OpCode.ping) {
            traceMask = ZooTrace.SERVER_PING_TRACE_MASK;
        }
        if (LOG.isTraceEnabled()) {
            for (int i = 0; i < request.length; i++)
                ZooTrace.logRequest(LOG, traceMask, 'E', request[i], "");
        }
        ProcessTxnResult[] rc = null;

        if (request[0].hdr != null) {
            TxnHeader[] header = new TxnHeader[request.length];
            Record[] txn = new Record[request.length];
            for (int i = 0; i < request.length; i++) {
                header[i] = request[i].hdr;
                txn[i] = request[i].txn;
            }
            rc = zks.getZKDatabase().processTxn(header, txn);
        }

        // do not add non quorum packets to the queue.
        if (Request.isQuorum(request[0].type)) {
            zks.getZKDatabase().addCommittedProposal(request);
        }

        String lastOp = "NA";
        zks.decInProcess();
        Code err = Code.OK;
        Record[] rsp = new Record[request.length];
        boolean closeSession = false;
        try {
            for (int i = 0; i < request.length; i++) {
                if (request[i].hdr != null && request[i].hdr.getType() == OpCode.error) {
                    throw KeeperException.create(KeeperException.Code
                            .get(((ErrorTxn) request[i].txn).getErr()));
                }

                KeeperException ke = request[i].getException();
                if (ke != null) {
                    throw ke;
                }

                if (LOG.isDebugEnabled()) {
                    LOG.debug(request);
                }
            }
            switch (request[0].type) {

                case OpCode.setData: {
                    //Do not responsd if this node is not in the quorum
                    //if (request.txn == null)
                    //    return;
                    //else
                    break;
                }

                case OpCode.sync: {
                    lastOp = "SYNC";
                    SyncRequest syncRequest = new SyncRequest();
                    ZooKeeperServer.byteBuffer2Record(request[0].request, syncRequest);
                    rsp[0] = new SyncResponse(syncRequest.getBlockId());
                    break;
                }

                case OpCode.getData: {
                    lastOp = "GETD";
                    long[] blockNo = new long[request.length];
                    for (int i = 0; i < request.length; i++) {
                        GetDataRequest getDataRequest = new GetDataRequest();
                        ZooKeeperServer.byteBuffer2Record(request[i].request,
                                getDataRequest);
                        blockNo[i] = getDataRequest.getBlockId();
                    }
                    byte b[][] = zks.getZKDatabase().getData(blockNo);
                    for (int i = 0; i < request.length; i++)
                        rsp[i] = new GetDataResponse(b[i]);
                    break;
                }

                case OpCode.boloskyGetData: {
                    if (Configuration.debug)
                        System.out.println("Process bolosky read " + request[0].zxid);
                    if (request[0].zxid < zks.getZKDatabase().getDataTreeLastProcessedZxid()) {
                        System.out.println("Discard old bolosky read zxid=" + request[0].zxid + " current=" + zks.getZKDatabase().getDataTreeLastProcessedZxid());
                        for (int i = 0; i < rsp.length; i++)
                            rsp[i] = new BoloskyGetDataResponse(new byte[0]);
                        break;
                    }
                    if (request[0].zxid > zks.getZKDatabase().getDataTreeLastProcessedZxid()) {
                        if (Configuration.debug)
                            System.out.println("Put bolosky read " + request[0].sessionId + " " + request[0].cxid + " " + Mapping.getBlockId(request[0])
                                    + " in queue zxid=" + request[0].zxid + " current=" + zks.getZKDatabase().getDataTreeLastProcessedZxid());
                        this.boloskyRead.addLast(request);
                        return;
                    }
                    lastOp = "GETD";
                    long[] blockNo = new long[request.length];
                    for (int i = 0; i < request.length; i++) {
                        request[i].request.rewind();
                        BoloskyGetDataRequest getDataRequest = new BoloskyGetDataRequest();
                        ZooKeeperServer.byteBuffer2Record(request[i].request,
                                getDataRequest);
                        blockNo[i] = getDataRequest.getBlockId();
                    }
                    byte b[][] = zks.getZKDatabase().getData(blockNo);
	start = System.currentTimeMillis();
                    for (int i = 0; i < b.length; i++) {
                        if (b[i] != null)
                            rsp[i] = new BoloskyGetDataResponse(b[i]);
                        else
                            rsp[i] = new BoloskyGetDataResponse(new byte[0]);
                    }
                    break;
                }

            }
        } catch (KeeperException e) {
            err = e.code();
        } catch (Exception e) {
            // log at error level as we are returning a marshalling
            // error to the user
            LOG.error("Failed to process " + request, e);
            StringBuilder sb = new StringBuilder();
            ByteBuffer bb = request[0].request;
            bb.rewind();
            while (bb.hasRemaining()) {
                sb.append(Integer.toHexString(bb.get() & 0xff));
            }
            LOG.error("Dumping request buffer: 0x" + sb.toString());
            err = Code.MARSHALLINGERROR;
        }
	
        for (int i = 0; i < request.length; i++) {
            ReplyHeader hdr = new ReplyHeader(request[i].cxid, request[i].nonce, request[i].type, request[i].zxid, err
                    .intValue());

            zks.serverStats().updateLatency(request[i].createTime);
            if (hdr.getType() == OpCode.setData)
                ReplyCache.addReply(request[i].sessionId, request[i].cxid, hdr, rsp[i], "response");

            ServerCnxn cnxn = zks.getServerCnxnFactory().getServerCnxn(request[i].sessionId);

            if (cnxn == null) {
                System.out.println("cnxn for " + request[i].sessionId + " is null");
                return;
            }

            ((CnxnStats) cnxn.getStats()).updateForResponse(request[i].cxid,
                    request[i].zxid, lastOp, request[i].createTime, System
                    .currentTimeMillis());

            try {

                //if (rc== null || rc[i] == null || rc[i].err != -3)
            	sender.put(hdr, rsp[i], cnxn);
                //cnxn.sendResponse(hdr, rsp[i], "response");
                if (closeSession) {
                    cnxn.sendCloseSession();
                }
            } catch (Exception e) {
                LOG.error("FIXMSG", e);
            }
        }
        if (request[0].type == OpCode.setData)
            this.checkBoloskyRead();
	//System.out.println("send response time="+(System.currentTimeMillis()-start)+" count="+request.length);
    }

    public void shutdown() {
        // we are the final link in the chain
        LOG.info("shutdown of request processor complete");
    }
    
    public static class SendResponseThread extends Thread{
    	private static class Reply{
    		ReplyHeader header;
    		Record rec;
    		ServerCnxn cnxn;
    	}
    	private LinkedBlockingQueue<Reply> queue = new LinkedBlockingQueue<Reply>();
    	
    	public void put(ReplyHeader header, Record rec, ServerCnxn cnxn){
    		Reply reply = new Reply();
    		reply.header=header;
    		reply.rec=rec;
    		reply.cnxn = cnxn;
    		try{
    			queue.put(reply);
    		}
    		catch(InterruptedException e){
    			e.printStackTrace();
    		}
    	}
    	
    	public void run(){
    		while(true){
    			try{
    				Reply reply = queue.take();
    				reply.cnxn.sendResponse(reply.header, reply.rec, "response");
                    if(reply.rec instanceof BoloskyGetDataResponse){
                        MemoryBuffer.deallocateBuffer(((BoloskyGetDataResponse)reply.rec).getData());
                    }
                }
    			catch(Exception e){
				LOG.warn("send ", e);
    			}
    		}
    	}
    }

}
